
const db=require("../db/index")

exports.storeHandler=(req,res)=>{
    if (!req.auth.id) {
        return res.R("登录过期!")
    }
    sql="select sid from store where uid=?"
    db.query(sql,[req.auth.id],(err,results)=>{
        if(err)return res.R(err)
        if (results.length<=0) return res.send("用户无收藏！")
        res.send({
            status:200,
            message:"查询收藏成功！",
            data:results
        })
    })
  
}

exports.storeListHandler=(req,res)=>{
    if (!req.auth.id) {
        return res.R("登录过期!")
    }
    const page=(Number(req.params.page)-1)*8
    sql=`select s.id,s.sourcename,s.sourcedescription,s.sourceimage,s.url,s.author,st.id as lid from source s 
    JOIN store st on (st.sid=s.id and st.uid=?) limit ?,8`
    db.query(sql,[req.auth.id,page],(err,results)=>{
        if (err) return res.R(err)
        if(results.length<=0)return res.R("暂无收藏！")
        res.send({
            status:200,
            data:results,
            message:"查询收藏列表成功！"
        })
    })
}
exports.addStore=(req,res)=>{
    let id=req.auth.id
    let sid=req.params.sid
    let sql="select id from store where uid = ? and sid = ?"
    db.query(sql,[id,sid],(err,results)=>{
        if (err) return res.R(err)
        if (results.length!==0){
            let storeid =results[0].id
            let removesql="delete from store where id = ?"
            db.query(removesql,[storeid],(err,results2)=>{
                if(err)return res.R(err)
                if(results2.affectedRows!==1)return res.R("移除收藏失败！")
                return res.send({
                    status:200,
                    message:"收藏已移除！"
                })
            })
        }
        else{
            let insertsql="insert into store (uid,sid) values(?,?)"
            db.query(insertsql,[id,sid],(err,results3)=>{
                if(err)return res.R(err)
                if(results3.affectedRows!==1)return res.R("添加收藏失败！")
                return res.send({
                    status:200,
                    message:"收藏成功！"
                })
            })
        }
    })

}